import java.io.*;
import java.nio.*;
import java.net.*;
import java.io.ByteArrayInputStream;
/**
 * 
 * @author rashminagaraju
 * This class listens on a port and receives UDP packets.
 * For each packet received, it prints the sequence number and receive 
 * timestamp
 */
public class Receiver extends Thread {
	public static final int MAX_PACKET_SIZE = 1490;
	private int numSecondsToWait;
	private int portNumber;
	private String logFile;
	
	public Receiver(int numSecondsToWait, int portNumber, String logFile)
	{
		this.numSecondsToWait = numSecondsToWait;
		this.portNumber = portNumber;
		this.logFile = logFile;
	}
	
	public void run()
	{
		try
		{
	    	DatagramSocket socket = new DatagramSocket(portNumber);
	    	socket.setSoTimeout(1000); //timeout after 1 sec if receive() is called and there is no incoming packet
	    	
	        ByteBuffer buf = ByteBuffer.allocate(MAX_PACKET_SIZE);
			PrintWriter out = new PrintWriter(new FileWriter(logFile));

			System.out.println("Started receiving on port " + portNumber);
			long start = System.currentTimeMillis();
			while(System.currentTimeMillis() < (start + numSecondsToWait*1000))
			{
		        //Reuse the same buffer for every packet
	        	buf.rewind();
	            DatagramPacket packet = new DatagramPacket(buf.array(), MAX_PACKET_SIZE);
	            try
	            {
	            	socket.receive(packet);
	            }
	            catch(SocketTimeoutException ste)
	            {
	            	continue;
	            }
	            
	            long recvTime = System.nanoTime();
	            //Read buffer from beginning
	            buf.rewind();
	            int seq = buf.getInt();
	            out.println(seq + "," + recvTime+","+(packet.getLength()));
	            System.out.println("Received packet "+seq+"...");
			}
			
			out.close();
			System.out.println("Finished receiving on port " + portNumber);

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
    public static void main(String[] args) throws Exception 
    {
    	if(args.length != 3)
    	{
    		System.err.println("Usage: java Receiver numSecondsToWait receiverPortNumber logFile");
    		return;
    	}
    	
    	Receiver receiver = new Receiver(Integer.parseInt(args[0]), Integer.parseInt(args[1]), args[2]);
    	receiver.start();
    }

}
